package com.example.connect;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.example.model.Contacts;
import com.example.model.Infications;
import com.example.model.MyNotifications;
import com.example.model.OutContacts;
import com.example.model.OutLogin;
import com.example.model.OutNotification;
import com.example.model.OutNotifications;
import com.example.model.OutProfile;
import com.example.model.OutResult;
import com.example.model.Profile;
import com.example.util.ConnectionException;
import com.example.util.EmptyDataException;
import com.example.util.TokenUnableException;

public class CallApi {
	  public static final String SERVER ="https://regform.guncms.de/buchmeo/buchmeo/api/";
	  public static final String REST_LOGIN  = "login";
	  public static final String REST_LOGOUT = "logout";
	  public static final String POST_GET_PROFILE = "get_profile";
	  public static final String REST_MY_PROFILE = "my_profile";
	  public static final String POST_REGISTER = "registry";
	  public static final String REST_CONTACT  = "contacts";
	  public static final String REST_NOTIFICATIONS = "notifications";
	  public static final String REST_REQUEST = "request";
	  public static final String POST_UPDATE_PROFILE = "update_profile";
	  public static final String REST_CANCEL_REQUEST  = "reject";
	  public static final String REST_ACCEPT_REQUEST  = "accept";
	  public static final String REST_MY_NOTIFICATIONS ="my_notifications";
	  
	  
	  public static final String JSON_NULL  = "Data empty !";
	  
	  private static String getString(JSONObject jsonObject,String name){
		  String tmp;
		try {
			tmp = jsonObject.isNull(name) ? "" : jsonObject.getString(name);
			 if(tmp == null )tmp ="";
		} catch (JSONException e) {
			tmp ="";
			e.printStackTrace();
		}
		 return tmp;
	  }
	  
	  public static OutLogin getLogin(Context context,String username,String password,String type) 
			     throws EmptyDataException, ConnectionException, JSONException, 
			     TokenUnableException{
		  OutLogin result = new OutLogin();
		   HashMap<String, String> data = new HashMap<String, String>();
		      data.put("email", username);
		      data.put("password", password);
		      data.put("type", type);
			HTTPReq htreq = new HTTPReq(SERVER);
			String json = htreq.post(context,REST_LOGIN, data);
				result = parserLogin(json);
		     return result;
	}
	  private static OutLogin parserLogin(String json){
		     OutLogin a = new OutLogin();
		     try
				{
					JSONObject c = new JSONObject(json);
					a.setMessage(getString(c, OutResult.MESSAGE));
					a.setStatus(getString(c,OutResult.STATUS));
					if(a.getStatus()){
						a.setReson(getString(c,OutResult.RESON));
						a.setToken(getString(c,"token"));
						a.setCode(getString(c,OutResult.CODE));
						OutProfile outProfile  =  new OutProfile();
						JSONObject jsonObject  = new JSONObject(getString(c,"profile"));
						
						outProfile.setId(getString(jsonObject,"id"));
						outProfile.setId_device(getString(jsonObject,"id_device"));
						outProfile.setId_contact(getString(jsonObject,"id_contact"));
						outProfile.setProperties(getString(jsonObject,"properties"));
						a.setProfile(outProfile);
					}else{
						a.setReson(getString(c,OutResult.RESON));
						a.setMessage(getString(c, OutResult.MESSAGE));
						return a;
					}
				}
				catch(Exception ex){
				    a.setStatus(false);
				    a.setMessage("Error :" + ex.getMessage());
					ex.printStackTrace();
				}
			
			return a;
		}
	/**
	 * 
	 * @param context
	 * @param data 
	 *  data only pass token get form login method
	 * @return
	 * 
	 */
	public static OutResult getLogout(Context context,List<String> data)
			 throws EmptyDataException, ConnectionException, JSONException, 
		     TokenUnableException{
		       OutResult result = new OutResult();
			    HTTPReq htreq = new HTTPReq(SERVER);
			    String json = htreq.get(context,REST_LOGOUT, data);
				result = parserLogout(json);
		     return result;
	}
	private static OutResult parserLogout(String json ){
	     OutResult a = new OutResult();
	     try
			{
				JSONObject c = new JSONObject(json);
				a.setMessage(getString(c, OutResult.MESSAGE));
				a.setStatus(getString(c,OutResult.STATUS));
				a.setCode(getString(c,OutResult.CODE));
				if(a.getStatus()){
					
				}else{
					a.setReson(getString(c,OutResult.RESON));
					return a;
				}
			}
			catch(Exception ex)
			{
			    a.setStatus(false);
			    a.setMessage("Error :" + ex.getMessage());
				ex.printStackTrace();
			}
		
		return a;
	}
	public static OutContacts getContacts(Context context,List<String> data) throws EmptyDataException, ConnectionException, JSONException, TokenUnableException{
		    OutContacts result = new OutContacts();
			HTTPReq htreq = new HTTPReq(SERVER);
			String json = htreq.get(context,REST_CONTACT, data);
			result = parserContacts(json);
		    return result;
	}
	  private static OutContacts parserContacts(String json ){
		  OutContacts a = new OutContacts();
		     try
				{
					JSONObject c = new JSONObject(json);
					a.setStatus(getString(c,OutResult.STATUS));
					a.setCode(getString(c,OutResult.CODE));
					if(a.getStatus()){
					 try{
						JSONArray array = new JSONArray(c.getString("contact"));
						for(int i =0; i< array.length(); ++i){
							JSONObject obJ  = array.getJSONObject(i);
							Contacts contact= new Contacts();
							contact.setId(getString(obJ, "id"));
							contact.setOwner(getString(obJ, "owner"));
							contact.setGender(getString(obJ, "gender"));
							contact.setFirstName(getString(obJ, "first_name"));
							contact.setLastName(getString(obJ, "last_name"));
							contact.setPhoneNumber(getString(obJ, "phone_number"));
							contact.setEmail(getString(obJ, "email"));
							contact.setWebsite(getString(obJ, "website"));
							contact.setCountry(getString(obJ, "country"));
							contact.setState(getString(obJ, "state"));
							contact.setPostCode(getString(obJ, "postcode"));
							contact.setCity(getString(obJ, "city"));
							contact.setAddress(getString(obJ, "address"));
							contact.setCompany(getString(obJ, "company"));
							contact.setBirthday(getString(obJ, "birthday"));
							contact.setAvatar(getString(obJ, "avatar"));
							contact.setMoreInfo(getString(obJ, "more_info"));
							a.addToListContact(contact);
						}
					 }catch(Exception e){
						 
					 }
					}else{
						a.setReson(getString(c,OutResult.RESON));
						return a;
					}
				}
				catch(Exception ex)
				{
				    a.setStatus(false);
				    a.setMessage("Error :" + ex.getMessage());
					ex.printStackTrace();
				}
			
			return a;
		}
	/**
	 * 
	 * @param context
	 * @param data 
	 *  data only pass token get form login method
	 *  
	 * @return
	 * 
	 */
	private static OutResult parserProfile(String json ){
		Log.e("SON", json);
		OutResult a = new OutResult();
		return a;
	}
	public static OutLogin getMyProfile(Context context,List<String> data){
		OutLogin result = new OutLogin();
		try {
			HTTPReq htreq = new HTTPReq(SERVER);
			String json = htreq.get(context,REST_MY_PROFILE, data);
			if (json == null) {
				result.setStatus(false);
				result.setMessage(JSON_NULL);
			} else {
				result = parserMyProfile(json);
			}
		} catch (Exception e) {
			result.setStatus(false);
		}
		return result;
	}
	
	
	private static OutLogin parserMyProfile(String json) {
		OutLogin a = null;
	     try
			{
	    	 a = new OutLogin();
				JSONObject c = new JSONObject(json);
				a.setStatus(getString(c,OutResult.STATUS));
				a.setMessage(getString(c, OutResult.MESSAGE));
				a.setCode(getString(c,OutResult.CODE));
				if(a.getStatus()){
					OutProfile outProfile  =  new OutProfile();
					JSONObject jsonObject  = new JSONObject(getString(c,"properties"));
					outProfile.setId(getString(jsonObject,"id"));
					outProfile.setId_device(getString(jsonObject,"id_device"));
					outProfile.setId_contact(getString(jsonObject,"id_contact"));
					outProfile.set_first_name(getString(jsonObject,"first_name"));
					outProfile.set_last_name(getString(jsonObject,"last_name"));
					outProfile.set_email(getString(jsonObject,"email"));
					outProfile.setProperties(getString(jsonObject,"properties"));
					a.setProfile(outProfile);
				}else{
					a.setReson(getString(c,OutResult.RESON));
					a.setMessage(getString(c, OutResult.MESSAGE));
					return a;
				}
			}
			catch(Exception ex)
			{
			    a.setStatus(false);
			    a.setMessage("Error :" + ex.getMessage());
				ex.printStackTrace();
			}
		
		return a;
	}

	public static OutResult getRegister(Context context,Map<String,String> hashMap)
			throws EmptyDataException, ConnectionException, JSONException, 
                   TokenUnableException {
		   OutResult result = new OutResult();
		
			HTTPReq htreq = new HTTPReq(SERVER);
			String json = htreq.post(context,POST_REGISTER, hashMap);
			Log.e("SON", "json: " + json);
				result = parserRegister(json);
		return result;
	}
	private static OutResult parserRegister(String json ){
		OutResult a = null;
		try
		{
			JSONObject c = new JSONObject(json);
			
			a = new OutResult();
			a.setStatus(!c.isNull(OutResult.STATUS)?c.getString(OutResult.STATUS):"");
			a.setCode(getString(c,OutResult.CODE));
			a.setMessage(!c.isNull(OutResult.MESSAGE)?c.getString(OutResult.MESSAGE):"");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return a;
	}
	
	// Update Profile
	public static OutResult getUpdateProfile(Context context,Map<String,String> hashMap, String token)
			throws EmptyDataException, ConnectionException, JSONException, 
            TokenUnableException {
		
		    OutResult result = new OutResult();
			HTTPReq htreq = new HTTPReq(SERVER);
			String json = htreq.post(context, POST_UPDATE_PROFILE+"/"+token, hashMap);
				result = parserRegister(json);
		return result;
	}
	private static OutResult parserUpdateProfile(String json ){
		OutResult a = null;
		try
		{
			JSONObject c = new JSONObject(json);
			a = new OutResult();
			a.setStatus(!c.isNull(OutResult.STATUS)?c.getString(OutResult.STATUS):"");
			a.setCode(getString(c,OutResult.CODE));
			a.setMessage(!c.isNull(OutResult.MESSAGE)?c.getString(OutResult.MESSAGE):"");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return a;
	}

	public static OutNotification getNotifications(Context context, List<String> data) throws
	             EmptyDataException, ConnectionException, 
	             JSONException, TokenUnableException{
		OutNotification result = new OutNotification();
		
			HTTPReq htreq = new HTTPReq(SERVER);
			String json = htreq.get(context,REST_NOTIFICATIONS, data);
			
				result = parserNotifications(json);
			
		return result;
	}
	

	private static OutNotification parserNotifications(String json) {
		OutNotification a = new OutNotification();
		try
		{
			JSONObject c = new JSONObject(json);
			a.setStatus(getString(c,OutResult.STATUS));
			a.setCode(getString(c,OutResult.CODE));
			if(a.getStatus()){
			 try{
				JSONArray array = new JSONArray(c.getString("notifications"));
				for(int i =0; i< array.length(); ++i){
					JSONObject obJ  = array.getJSONObject(i);
					Infications infication= new Infications();
					infication.setStatus(getString(obJ, "status"));
				    infication.setDateCreate(getString(obJ,"date_create"));
					infication.setId(getString(obJ, "id"));
					infication.setIs_acitve(getString(obJ, "is_active"));
					JSONObject jsonObjForm  = obJ.getJSONObject("from");
					Profile form  = new Profile();
						form.setId(getString(jsonObjForm,"id"));
						form.setActiveCode(getString(jsonObjForm,"active_code"));
						form.setDateCreate(getString(jsonObjForm,"date_create"));
						form.setEmail(getString(jsonObjForm,"email"));
						form.setFullName(getString(jsonObjForm,"full_name"));
						form.setGroup(getString(jsonObjForm,"groups"));
						form.setIsActive(getString(jsonObjForm,"is_active"));
						form.setLastLogin(getString(jsonObjForm,"last_login"));
						form.setLastName(getString(jsonObjForm,"last_name"));
						form.setPassword(getString(jsonObjForm,"password"));
						form.setSalt(getString(jsonObjForm,"salt"));
						form.setUsername(getString(jsonObjForm,"username"));
						//form.setProperties(getString(jsonObjForm,"id"));
					JSONObject jsonObjTo  = obJ.getJSONObject("to");
					Profile to  = new Profile();
					to.setId(getString(jsonObjTo,"id"));
					to.setActiveCode(getString(jsonObjTo,"active_code"));
					to.setDateCreate(getString(jsonObjTo,"date_create"));
					to.setEmail(getString(jsonObjTo,"email"));
					to.setFullName(getString(jsonObjTo,"full_name"));
					to.setGroup(getString(jsonObjTo,"groups"));
					to.setIsActive(getString(jsonObjTo,"is_active"));
					to.setLastLogin(getString(jsonObjTo,"last_login"));
					to.setLastName(getString(jsonObjTo,"last_name"));
					to.setPassword(getString(jsonObjTo,"password"));
					to.setSalt(getString(jsonObjTo,"salt"));
					to.setUsername(getString(jsonObjTo,"username"));
					//form.setProperties(getString(jsonObjForm,"id"));
					infication.setForm(form);   
					infication.setTo(to);
					if(infication.getIs_acitve().equals("1"))
						a.addToListNotification(infication);
				}
			 }catch(Exception e){
				 
			 }
			}else{
				a.setReson(getString(c,OutResult.RESON));
				a.setMessage(getString(c, OutResult.MESSAGE));
				return a;
			}
		}
		catch(Exception ex)
		{
		    a.setStatus(false);
		    a.setMessage("Error :" + ex.getMessage());
			ex.printStackTrace();
		}
	
	return a;
}
	

	public static Object updateMyProfile(Context context,List<String> data) {
		
		return null;
	}
   
	public static OutResult sendRequest(Context context,List<String> data)
		 throws EmptyDataException, ConnectionException, JSONException, 
         TokenUnableException{
		OutResult result = new OutResult();
		
			HTTPReq htreq = new HTTPReq(SERVER);
			String json = htreq.get(context,REST_REQUEST, data);
				result = parserSendRequest(json);
		return result;
	}
	private static OutResult parserSendRequest(String json){
		OutResult a = new OutResult();
		try
		{
			JSONObject c = new JSONObject(json);
			a = new OutResult();
			a.setStatus(!c.isNull(OutResult.STATUS)?c.getString(OutResult.STATUS):"");
			a.setCode(getString(c,OutResult.CODE));
			a.setMessage(!c.isNull(OutResult.MESSAGE)?c.getString(OutResult.MESSAGE):"");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return a;
	}
	public static OutResult sendRejectRequest(Context context,List<String> data) 
			         throws EmptyDataException, ConnectionException, JSONException, 
			                 TokenUnableException{
		OutResult result = new OutResult();
		
			HTTPReq htreq = new HTTPReq(SERVER);
			String json = htreq.get(context,REST_CANCEL_REQUEST, data);
			
				result = parserRejectRequest(json);
			
		return result;
	}
	private static OutResult parserRejectRequest(String json){
		OutResult a = new OutResult();
		try
		{
			JSONObject c = new JSONObject(json);
			a = new OutResult();
			a.setStatus(!c.isNull(OutResult.STATUS)?c.getString(OutResult.STATUS):"");
			a.setCode(getString(c,OutResult.CODE));
			a.setMessage(!c.isNull(OutResult.MESSAGE)?c.getString(OutResult.MESSAGE):"");
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return a;
	}

	public static OutResult sendAcceptRequest(
			Context context, List<String> data)
					 throws EmptyDataException, ConnectionException,
					        JSONException, TokenUnableException {
		
			OutResult result = new OutResult();
			
				HTTPReq htreq = new HTTPReq(SERVER);
				String json = htreq.get(context,REST_ACCEPT_REQUEST, data);
				
					result = parserRejectRequest(json);
				
			return result;
		}
	public static Object getProfile(Context context, Map<String,String> hashMap, String token) {
		OutResult result = new OutResult();
		try {
			HTTPReq htreq = new HTTPReq(SERVER);
			String json = htreq.post(context, POST_GET_PROFILE+"/"+token, hashMap);
			if (json == null) {
				result.setStatus(false);
				result.setMessage(JSON_NULL);
			} else {
				result = parserGetProfile(json);
			}
		} catch (Exception e) {
			result.setStatus(false);
			result.setMessage("Error when connect to server");
		}
		return result;
	}
	
	private static OutResult parserGetProfile(String json ){
		OutResult a = null;
		try
		{
//			JSONObject c = new JSONObject(json);
//			
//			a = new OutResult();
//			a.setStatus(!c.isNull(OutResult.STATUS)?c.getString(OutResult.STATUS):"");
//			a.setMessage(!c.isNull(OutResult.MESSAGE)?c.getString(OutResult.MESSAGE):"");
			Log.e("GET_PROFILE", json);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return a;
	}

public static Object getMyNotifications(Context context, List<String> data) 
		 throws EmptyDataException, ConnectionException,
	        JSONException, TokenUnableException {
	     OutResult result = new OutResult();
	
		HTTPReq htreq = new HTTPReq(SERVER);
		String json = htreq.get(context,REST_MY_NOTIFICATIONS, data);
			result = parserMyNotifications(json);
	   return result;
}


private static OutNotifications parserMyNotifications(String json) {
	OutNotifications a = new OutNotifications();
	try
	{
		JSONObject c = new JSONObject(json);
		a.setStatus(getString(c,OutResult.STATUS));
		a.setCode(getString(c,OutResult.CODE));
		if(a.getStatus()){
			try {
			      JSONArray array = new JSONArray(c.getString("notifications"));
			       for(int i =0; i< array.length(); ++i){
						JSONObject obJ  = array.getJSONObject(i);
						MyNotifications temp  = new MyNotifications();
						temp.setEmail(getString(obJ, "to"));
						temp.setStatus(getString(obJ,"status"));
						a.getList().add(temp);
		          }
			 }catch (Exception  e){
				  
			 }
			return a;
		}else{
			a.setReson(getString(c,OutResult.RESON));
			a.setMessage(getString(c, OutResult.MESSAGE));
			return a;
		}
	}
	catch(Exception ex)
	{
	    a.setStatus(false);
	    a.setMessage("Error :" + ex.getMessage());
		ex.printStackTrace();
	}

    return a;
  }
}